<?php

namespace AuctionBack\Controller;

use AuctionCore\Other\Address;
use Think\Controller;
use AuctionCore\System\AuctionException;
use AuctionCore\Account\Back\Employee;
use AuctionCore\Account\Back\EmpLoginLog;
use AuctionCore\Account\UniqLogin;
use AuctionCore\System\Menu;

/**
 * 后台抽象控制器
 * 为防止多分组Controller名称冲突，公共Controller名称统一使用分组名称
 */
class BaseController extends Controller
{

    protected $user_info = '';
    protected $is_hq = null; //是否为总部
    protected $bc_city = null; //所在地列表
    protected $exclude_c = array(
        'C_EMP|A_GETAUTHCODE'
    );

    //初始化
    public function __construct()
    {
        parent::__construct();
        $ca = strtoupper('C_' . CONTROLLER_NAME . "|A_" . ACTION_NAME);
        if (!in_array($ca, $this->exclude_c)) {
            $this->initSession();
            $this->user_info = session('user_info');
            if (!is_array($this->user_info['bc_code'])) {
                unset($this->user_info);
            }
            //登录验证
            $this->isLogin();
            $this->assign("user_info", $this->user_info);
            //检查权限
            $this->checkAuth();
            //检查唯一登录
            $this->checkUniqueLogin();
            //所在地
            $a = new Address();
            $this->bc_city = $a->get_apply_city();
            //print_r($this->bc_city);
            $this->is_hq = is_array($this->user_info['bc_code']) && empty($this->user_info['bc_code']) ? true : false;
            if (!$this->is_hq && !empty($this->user_info['bc_code']) && !empty($this->user_info['bc_name'])) {
                $this->bc_city = array_combine($this->user_info['bc_code'], $this->user_info['bc_name']);
            }
            $this->assign('is_hq', $this->is_hq);
            $this->assign('bc_city', $this->bc_city);
            //找到角色所拥有权限栏目
            $e = new Employee($this->user_info['username']);
            $auth = $e->get_emp_auth();
            $tree_menu = Menu::build_tree_menu($auth);
            $this->assign('tree_menu', $tree_menu);
        }
    }

    /*
    * @param $name 权限名
    * 检查ACTION权限
    */
    public function checkAuth($name = false)
    {
        try {
            if (!$name) {
                $AUTH_CONFIG = C('AUTH_CONFIG');
                $a_key = strtoupper('C_' . CONTROLLER_NAME . "|A_" . ACTION_NAME);
                if (!array_key_exists($a_key, $AUTH_CONFIG)) {
                    return;
                }
                $name = $AUTH_CONFIG[$a_key];
            }
            $user_info = $this->user_info;
            $e = new Employee($user_info['username']);
            $ok = $e->check_auth($name);
            if (!$ok) { //无权限
                AuctionException::make_throw('300008');
            }
        } catch (AuctionException $e) {
            $this->error($e->getMessage());
            exit;
        }
    }

    public function initSession()
    {
        $user_info = cookie('user_info');
        if ($user_info) {
            $user_info = json_decode(urldecode($user_info), true);
            $session_verify_key = sha1(C('DB_HOST') . $user_info['emp_id']);
            if ($user_info['ver_key'] == $session_verify_key) {
                session('user_info', $user_info);
            }
        }
    }

    private function isLogin()
    {
        $exclude = array('/Emp/login', '/Emp/ci_login', '/Notify/refund', '/Notify/OilPayRefund');
        if (in_array(__ACTION__, $exclude)) {
            return;
        }
        if (!$this->user_info) {
            redirect(U('Emp/login')); //去登录
        }
    }

    /**
     *  JSON输出
     * @param int $code
     * @param string $message
     * @param string $data
     */
    public function helpJsonResult($code = 200, $message = '', $data = "")
    {
        echo json_encode(array('code' => $code, "msg" => $message, 'data' => $data), JSON_UNESCAPED_UNICODE);
        exit;
    }

    /**
     * 获取所有分公司列表
     */
    public function get_branch_company_list()
    {
        $bc_list = array();
        if (!$this->is_hq) {
            $bc_list_data[] = \AuctionCore\Account\Back\Department::getDepartById($this->user_info['branch_id']);
            foreach ($bc_list_data as $k => $v) {
                $bc_list[$v['id']] = $v['name'];
            }
        } else {
            $bc_list_data = \AuctionCore\Account\Back\Department::getBranchCompanyList();
            foreach ($bc_list_data as $k => $v) {
                $bc_list[$v['id']] = $v['name'];
            }
        }
        return $bc_list;
    }

    /**
     * js 跳转 并 提示
     * @param string $message
     * @param string $script
     */
    protected function helpJsRedirect($message = '', $script = "history.back();")
    {
        $html = '';
        if (!empty($message)) {
            header("content-type: text/html; charset=utf-8");
            $message = str_replace("\n", "\\n", $message);
            $html .= "<script language=\"javascript\">";
            $html .= "alert(\"{$message}\");";
            $html .= "</script>";
        }
        $html .= "<script language=\"javascript\">";
        $html .= $script;
        $html .= "</script>";
        die($html);
    }


    /**
     * 获取渠道来源信息
     */
    public function get_comefrom_list()
    {
        $from = M('come_from')->field('from_id,pid,from_name')
            ->where('pid=-2 AND is_delete=0')
            ->select();
        $show_from = array();
        foreach ($from as $key => $val) {
            $child_from = M("come_from a")->field("a.from_id,a.from_name,b.sort AS psort")
                ->join('(SELECT from_id,from_name,sort FROM au_come_from WHERE pid=-2 AND is_delete=0) AS b ON a.pid=b.from_id')
                ->where("a.pid!=-2 AND a.is_delete=0")
                ->where("a.pid=" . $val['from_id'])
                ->order("psort ASC,from_id ASC,pid DESC")
                ->select();
            $show_from[$val['from_id']] = $child_from;
        }
        return $show_from;
    }

    /**
     * 城市对应的4s店
     */
    public function get_fours_by_city()
    {
        $bc_city = $this->bc_city;
        $city_fours_list = array();
        foreach ($bc_city as $kb => $vb) {
            $city_fours = M("come_from")->alias('a')->field('a.from_id,a.from_name')
                ->join(C('DB_PREFIX') . 'fours as f ON a.from_id = f.channel_id')
                ->where(array('f.city' => $kb))
                ->order('from_id ASC,pid DESC')
                ->select();
            $city_fours_list[$kb] = $city_fours;
        }
        return $city_fours_list;
    }

    //检查互斥登录
    private function checkUniqueLogin()
    {
        if (!$this->user_info) {
            return;
        }
        $ul = new UniqLogin();
        $ok = $ul->check($this->user_info['emp_id'], $this->user_info['uniq_login_token']);
        if (!$ok) {
            session('user_info', null);
            cookie('user_info', null);
            header('location:/');
        }

        //更新登录活动记录
        EmpLoginLog::up_act_time(sha1($this->user_info['uniq_login_token']));
    }
}